using AutoMapper;
using Finance.Api.Write.Applications.Commands.库存盘点;
using Finance.Domain.盘点;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Write.Applications.CommandHands.库存盘点
{
    public class CheckAddCommandHandler : IRequestHandler<CheckAddCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<CheckModel> db;
        private readonly SqlsugarDb<Detail> dc;
        private readonly IMapper mapper;

        public CheckAddCommandHandler(SqlsugarDb<CheckModel> db, IMapper mapper, SqlsugarDb<Detail> dc)
        {
            this.db = db;
            this.mapper = mapper;
            this.dc = dc;
        }

        public async Task<ApiResult<int>> Handle(CheckAddCommand request, CancellationToken cancellationToken)
        {
            
            var result = new ApiResult<int>();
            try
            {
                if (string.IsNullOrEmpty(request.Checkno))
                {
                    result.Code = Enumcode.Nonull;
                    result.message = "盘点编号不能为空";
                    return result;
                }

                var addResult = mapper.Map<CheckModel>(request);
                addResult.CreateTime = DateTime.Now;
                addResult.CreateName = "管理员"; // 固定值
                addResult.LoginId = 1; // 固定值

                var dateilentity = mapper.Map<List<Detail>>(request.DetailList);
                var rows = await db.BeginTransaction(async () =>
                {
                    var EntityId = await db.AddReturnId(addResult);
                    if (EntityId == 0)
                    {
                        result.message = "添加失败";
                        result.data = 0;
                        result.Code = Enumcode.fail;
                    }

                    foreach (var item in dateilentity)
                    {
                        item.checkid = EntityId;

                    }
                    var dateilreturn = await dc.Addlist(dateilentity);
                    return dateilreturn;


                  
                });
             
                if (rows > 0)
                {
                    result.message = "添加成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "添加失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.data = 0;
                result.Code = Enumcode.fail;
            }

            return await Task.FromResult(result);
        }
    }
} 